package cn.sczhyt.modules.szhy.service.impl;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.DateUtils;
import cn.sczhyt.common.utils.UUIDUtils;
import cn.sczhyt.modules.szhy.dao.MeetingNoticeReceiveDao;
import cn.sczhyt.modules.szhy.entity.MeetingFileEntity;
import cn.sczhyt.modules.szhy.entity.MeetingNoticeReceiveEntity;
import cn.sczhyt.modules.szhy.entity.VO.MeetingNoticeEntitySaveVO;
import net.sf.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.common.utils.PageUtils;
import cn.sczhyt.common.utils.Query;

import cn.sczhyt.modules.szhy.dao.MeetingNoticeDao;
import cn.sczhyt.modules.szhy.entity.MeetingNoticeEntity;
import cn.sczhyt.modules.szhy.service.MeetingNoticeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import static cn.sczhyt.common.utils.ShiroUtils.getUserId;
import static cn.sczhyt.common.utils.ShiroUtils.getUsername;


@Service("meetingNoticeService")
public class MeetingNoticeServiceImpl extends ServiceImpl<MeetingNoticeDao, MeetingNoticeEntity> implements MeetingNoticeService {

    @Autowired
    private MeetingNoticeReceiveDao receiveDao;

    @Autowired
    private MeetingNoticeDao meetingNoticeDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MeetingNoticeEntity> page = this.page(
                new Query<MeetingNoticeEntity>().getPage(params),
                new QueryWrapper<MeetingNoticeEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void publish(MeetingNoticeEntitySaveVO meetingNoticeEntitySaveVO) {


        MeetingNoticeEntity meetingNotice = new MeetingNoticeEntity();

        BeanUtils.copyProperties(meetingNoticeEntitySaveVO,meetingNotice);

        meetingNotice.setNoticePublisherId(getUserId());
        meetingNotice.setNoticePublisherName(getUsername());
        meetingNotice.setNoticePublishDatetime(new Date());

        this.baseMapper.insert(meetingNotice);


        String noticeReceiver = meetingNoticeEntitySaveVO.getNoticeReceiver();

        JSONArray jsonArray = JSONArray.fromObject(noticeReceiver);

        //保存对应接收人
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                String receiverId = jsonArray.getJSONObject(i).getString("userId");
                String receiverName = jsonArray.getJSONObject(i).getString("username");
                MeetingNoticeReceiveEntity receiveEntity = new MeetingNoticeReceiveEntity();

                receiveEntity.setNoticeId(meetingNotice.getNoticeId());
                receiveEntity.setNoticeReceiverId(receiverId);
                receiveEntity.setNoticeReceiverName(receiverName);
                receiveEntity.setNoticeReceiveStatus(false);

                receiveDao.insert(receiveEntity);
            }

        }



    }

    @Override
    public void updateByNoticeId(MeetingNoticeEntitySaveVO meetingNoticeEntitySaveVO) {



        MeetingNoticeEntity meetingNotice = new MeetingNoticeEntity();

        BeanUtils.copyProperties(meetingNoticeEntitySaveVO,meetingNotice);

        meetingNotice.setNoticePublisherId(getUserId());
        meetingNotice.setNoticePublisherName(getUsername());
        meetingNotice.setNoticePublishDatetime(new Date());

        this.baseMapper.updateById(meetingNotice);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByNoticeIds(List<String> list) {

        for (int i = 0; i < list.size(); i++) {
            //删除通知公告
            QueryWrapper<MeetingNoticeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("notice_id",list.get(i));
            this.baseMapper.delete(queryWrapper);
            //删除所以接收人
            QueryWrapper<MeetingNoticeReceiveEntity> receiveEntityQueryWrapper = new QueryWrapper<>();
            receiveEntityQueryWrapper.eq("notice_id",list.get(i));
            receiveDao.delete(receiveEntityQueryWrapper);
        }

    }

    @Override
    public void upload(MultipartFile[] files) {
        if (files != null && files.length > 0) {
            //根据时间创建文件夹
            Date date = new Date();
            String datefile = DateUtils.format(date, "yyyyMMdd");
            //创建文件名
            String filename = UUIDUtils.getUUID();
            //会议文件存储的路径

            String realPath = "D:\\zhyt-szhy".concat(datefile);
//            String realPath = "/var/szhy/file/".concat(datefile);
            File path = new File(realPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                System.out.println("文件大小为:" + file.getSize() / 1024);
                //保存文件
                if (!file.isEmpty()) {
                    try {
                        //转存文件 file.getOriginalFilename()：文件原名称包括后缀名
                        String originalFilename = file.getOriginalFilename();
                        //原文件名的后缀名
                        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        //文件存储位置
                        String filepath = realPath + "/" + filename + "." + substring;

                        System.out.println(filepath);

                        file.transferTo(new File(filepath));
//
//                        //上传成功后对路径及文件名进行处理
//                        MeetingFileEntity meetingFileEntity = new MeetingFileEntity();
//                        meetingFileEntity.setMeetingId(meetingId);
//                        meetingFileEntity.setFileName(originalFilename);
//                        meetingFileEntity.setFilePath(filepath);
//                        meetingFileEntity.setFileSize((int) (file.getSize() / 1024));
//                        meetingFileEntity.setCreateTime(new Date());
//                        meetingFileDao.insert(meetingFileEntity);

                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RRException("会议文件保存失败!", 201);
                    }
                }
            }
        }
    }

}